package it.disim.tlp.webreputation.aggregatorplugin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

public class PluginLoader{
  private AggregatorPlugin pa;
  private URLClassLoader ucl;

  public PluginLoader(String folder, String JarFile, String[] libs, String JarClass) 
	         throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

	  	String PluginDirectory = "plugins/"+folder+'/';
	  	
	  	/*main plugin jar loading*/
	  	File PluginFile = new File(PluginDirectory);
	    PluginFile = new File(PluginFile,JarFile);
	    if (!PluginFile.exists())
	      throw new FileNotFoundException("Jar File " + JarFile + " Not Found!");
	    
	    URL[] classPathUrl = new URL[1];
	    
	    /* if libs array is not null or empty additional libs are loaded*/
	    if(libs != null || libs.length != 0){
	    	File[] libsFile = new File[libs.length];
	    	classPathUrl = new URL[libs.length+1];
	    	for(int i= 0; i < libs.length; i++){
	    		libsFile[i] = new File(PluginDirectory);
	    		libsFile[i] = new File(libsFile[i],libs[i]);
	    		if(!libsFile[i].exists())
	    			throw new FileNotFoundException("Jar File" + libs[i] + "Not Found!");
	    		classPathUrl[i] = libsFile[i].toURI().toURL();
	    	}
	    }
	    
	    /*classpath loading*/
	    classPathUrl[classPathUrl.length-1] = PluginFile.toURI().toURL();
	    ucl = new URLClassLoader(classPathUrl);	 
		Class<?> JarLoadedClass = ucl.loadClass(JarClass);
		pa = (AggregatorPlugin) JarLoadedClass.newInstance();
  }
  
  public AggregatorPlugin getPlugin(){
	  return pa;
  }
  
  public void closePlugin() throws IOException{
	  /*close plugin and all other releated stuff like files etc*/
	  ucl.close();
  }
  
}